<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="所属库区" prop="areaId">
        <el-select
          v-model="queryParams.areaId"
          placeholder="请输入所属库区"
          clearable
          style="width: 150px"
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="dict in areaList"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="库位名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入库位名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库位状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择库位状态"
          clearable
          style="width: 150px"
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="dict in status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['basics:location:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['basics:location:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['basics:location:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['basics:location:export']"
          >下载库区模板</el-button
        >
      </el-col>
      <el-button
        type="warning"
        plain
        icon="Upload"
        @click="handleExcelImport"
        v-hasPermi="['basics:location:import']"
        >导入库区信息</el-button
      >
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="locationList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="所属仓库" align="center" prop="wname" />
      <el-table-column label="所属库区" align="center" prop="aname" />
      <el-table-column label="库位编码" align="center" prop="code" />
      <el-table-column label="库位名称" align="center" prop="name" />
      <el-table-column label="温度类型" align="center" prop="temperatureType">
        <template #default="scope">
          <dict-tag
            :options="temperature_type"
            :value="scope.row.temperatureType"
          />
        </template>
      </el-table-column>
      <el-table-column label="承重类型" align="center" prop="bearingType">
        <template #default="scope">
          <dict-tag :options="bearing_type" :value="scope.row.bearingType" />
        </template>
      </el-table-column>
      <el-table-column label="用途类型" align="center" prop="useType">
        <template #default="scope">
          <dict-tag :options="use_type" :value="scope.row.useType" />
        </template>
      </el-table-column>
      <el-table-column label="承载上限" align="center" prop="maxNum" />
      <el-table-column label="停用状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['basics:location:edit']"
            >修改</el-button
          >
          <el-button type="primary" link @click="handleToggleStatus(scope.row)">
            <span v-if="scope.row.status === 1">启用</span>
            <span v-if="scope.row.status === 0">停用</span>
          </el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['basics:location:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库位管理对话框 -->
    <el-dialog :title="title" v-model="open" append-to-body>
      <el-form ref="locationRef" :model="form" :rules="rules">
        <el-form-item label="库位编码" prop="code">
          {{ form.code }}
        </el-form-item>
        <el-form-item label="库区">
          <el-select
            v-model="form.areaId"
            style="width: 525px"
            placeholder="请选择库区名称"
          >
            <el-option
              v-for="dict in areaList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库位名称" prop="name">
          <el-input
            v-model="form.name"
            style="width: 500px"
            placeholder="请输入库位名称"
          />
        </el-form-item>
        <el-form-item label="温度类型" prop="temperatureType">
          <el-select
            v-model="form.temperatureType"
            style="width: 500px"
            placeholder="请选择温度类型"
          >
            <el-option
              v-for="dict in temperature_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="承重类型" prop="bearingType">
          <el-select
            v-model="form.bearingType"
            style="width: 500px"
            placeholder="请选择承重类型"
          >
            <el-option
              v-for="dict in bearing_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用途类型" prop="useType">
          <el-select
            v-model="form.useType"
            style="width: 500px"
            placeholder="请选择用途类型"
          >
            <el-option
              v-for="dict in use_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="停用状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in status"
              :key="dict.value"
              :label="parseInt(dict.value)"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="承载上限" prop="maxNum">
          <el-input
            v-model="form.maxNum"
            style="width: 450px"
            placeholder="请输入承载上限"
          />&emsp;m²
        </el-form-item>
        <el-form-item label="承载体积" prop="maxVolume">
          <el-input
            v-model="form.maxVolume"
            style="width: 450px"
            placeholder="请输入承载体积"
          />&emsp; 个
        </el-form-item>
        <el-form-item label="承载重量" prop="maxWeight">
          <el-input
            v-model="form.maxWeight"
            style="width: 450px"
            placeholder="请输入承载重量"
          />
          &emsp; kg
        </el-form-item>
        <el-form-item label="库位排/列/层" prop="locationRow">
          <el-input
            v-model="form.locationRow"
            style="width: 150px"
            placeholder="请输入排"
          />
          &emsp;
          <el-input
            v-model="form.locationColumn"
            style="width: 150px"
            placeholder="请输入列"
          />
          &emsp;
          <el-input
            v-model="form.locationLayer"
            style="width: 150px"
            placeholder="请输入层"
          />
        </el-form-item>
        <el-form-item label="库位长/宽/高" prop="locationLength">
          <el-input
            v-model="form.locationLength"
            style="width: 150px"
            placeholder="请输入长"
          />
          &emsp;
          <el-input
            v-model="form.locationWidth"
            style="width: 150px"
            placeholder="请输入宽"
          />
          &emsp;
          <el-input
            v-model="form.locationHigh"
            style="width: 150px"
            placeholder="请输入高"
          />
          &emsp; cm
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <div>
    <!-- 数据导入对话框 -->
    <el-dialog title="数据导入" v-model="excelOpen" append-to-body>
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        :action="uploadExcelUrl"
        :headers="headers"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="handleBeforeUpload"
        :limit="1"
        :auto-upload="false"
      >
        <template #trigger>
          <el-button type="primary">上传文件</el-button>
        </template>
        &emsp;
        <el-button class="ml-3" type="success" @click="submitUpload">
          上传
        </el-button>
        <template #tip>
          <div class="el-upload__tip">
            上传文件仅支持,xls/xlsx格式,文件大小不得超过1M
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup name="Location">
import {
  listLocation,
  getLocation,
  delLocation,
  addLocation,
  updateLocation,
  updateLocationStatus,
  generateLocationCode,
} from "@/api/basics/location";
import { getToken } from "@/utils/auth";

import { ElMessageBox, ElMessage } from "element-plus";
import { listArea } from "@/api/basics/area";
const { proxy } = getCurrentInstance();
const { temperature_type, status, bearing_type, use_type } = proxy.useDict(
  "temperature_type",
  "status",
  "bearing_type",
  "use_type"
);

const locationList = ref([]);
const areaList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    areaId: null,
    name: null,
    status: null,
  },
  rules: {
    areaId: [{ required: true, message: "所属库区不能为空", trigger: "blur" }],
    name: [{ required: true, message: "库位名称不能为空", trigger: "blur" }],
    temperatureType: [
      { required: true, message: "温度类型不能为空", trigger: "change" },
    ],
    bearingType: [
      { required: true, message: "承重类型不能为空", trigger: "change" },
    ],
    useType: [
      { required: true, message: "用途类型不能为空", trigger: "change" },
    ],
    maxNum: [{ required: true, message: "承载上限不能为空", trigger: "blur" }],
    maxVolume: [
      { required: true, message: "承载体积不能为空", trigger: "blur" },
    ],
    maxWeight: [
      { required: true, message: "承载重量不能为空", trigger: "blur" },
    ],
    locationRow: [{ required: true, message: "排不能为空", trigger: "blur" }],
    locationColumn: [
      { required: true, message: "列不能为空", trigger: "blur" },
    ],
    locationLayer: [{ required: true, message: "层不能为空", trigger: "blur" }],
    locationLength: [
      { required: true, message: "长不能为空", trigger: "blur" },
    ],
    locationWidth: [{ required: true, message: "宽不能为空", trigger: "blur" }],
    locationHigh: [{ required: true, message: "高不能为空", trigger: "blur" }],
    status: [
      { required: true, message: "停用状态不能为空", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询库位管理列表 */
function getList() {
  loading.value = true;
  listLocation(queryParams.value).then((response) => {
    locationList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
  listArea(queryParams.value).then((response) => {
    areaList.value = response.rows;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    ownerId: null,
    warehouseId: null,
    areaId: null,
    code: null,
    name: null,
    temperatureType: null,
    bearingType: null,
    useType: null,
    useStatus: null,
    maxNum: null,
    maxVolume: null,
    maxWeight: null,
    locationRow: null,
    locationColumn: null,
    locationLayer: null,
    locationLength: null,
    locationWidth: null,
    locationHigh: null,
    frozen: null,
    status: null,
    remark: null,
    createUser: null,
    createName: null,
    createTime: null,
    updateUser: null,
    updateName: null,
    updateTime: null,
    logicDel: null,
  };
  proxy.resetForm("locationRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
async function handleAdd() {
  reset();
  try {
    const res = await generateLocationCode();
    console.log("生成编码结果:", res);
    form.value.code = res;
  } catch (error) {
    ElMessage.error("生成库区编码失败");
  }
  open.value = true;
  title.value = "添加库位管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getLocation(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改库位管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["locationRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateLocation(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addLocation(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除库位管理编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delLocation(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "basics/location/export",
    {
      ...queryParams.value,
    },
    `location_${new Date().getTime()}.xlsx`
  );
}

const handleToggleStatus = async (row) => {
  // 弹窗文案
  const status = row.status === 1 ? "启用" : "停用";
  const newStatus = row.status;
  try {
    // 1. 弹出确认弹窗（修正：需要await获取用户操作结果）
    await ElMessageBox.confirm(`确认${status}仓库${row.name}吗？`, "操作确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    // 2. 调用后端接口（修正：传递正确的参数）
    const res = await updateLocationStatus(row.id, newStatus);

    if (res.code === 200) {
      // 更新本地状态
      // row.status = newStatus;
      ElMessage.success(`${status}成功`);
      getList();
    } else {
      ElMessage.error(res.msg || "操作失败");
    }
  } catch (error) {
    // 取消操作
    if (error.name === "Cancel") {
      ElMessage.info("已取消操作");
    } else {
      console.error("状态更新失败:", error);
      ElMessage.error("操作失败，请重试");
    }
  }
};

/* 打开数据导入对话框 */
const excelOpen = ref(false);
function handleExcelImport() {
  excelOpen.value = true;
}
/* 上传地址 */
const uploadExcelUrl = ref(
  import.meta.env.VITE_APP_BASE_API + "/basics/location/import"
); // 上传excel文件地址
/* 上传请求头 */
const headers = ref({ Authorization: "Bearer " + getToken() });

/* 上传excel */
const uploadRef = ref({});
function submitUpload() {
  uploadRef.value.submit();
}

const props = defineProps({
  modelValue: [String, Object, Array],
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 1,
  },
  // 文件类型, 例如["xls", "xlsx"]
  fileType: {
    type: Array,
    default: () => ["xls", "xlsx"],
  },
});

// 上传前loading加载
function handleBeforeUpload(file) {
  let isExcel = false;
  if (props.fileType.length) {
    let fileExtension = "";
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    isExcel = props.fileType.some((type) => {
      if (file.type.indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
  }
  if (!isExcel) {
    proxy.$modal.msgError(
      `文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`
    );
    return false;
  }
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`上传excel大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy.$modal.loading("正在上传excel，请稍候...");
}

// 上传失败
function handleUploadError() {
  proxy.$modal.msgError("上传excel失败");
  uploadRef.value.clearFiles();
  proxy.$modal.closeLoading();
}

// 上传成功回调
function handleUploadSuccess(res, file) {
  if (res.code === 200) {
    proxy.$modal.msgSuccess("上传excel成功");
    excelOpen.value = false;
    getList();
  } else {
    proxy.$modal.msgError("res.msg");
  }
  uploadRef.value.clearFiles();
  proxy.$modal.closeLoading();
}
getList();
</script>
